package syncmethod;

//儿子接口类
class Son implements Runnable {

    private IceBox iceBox; //冰箱对象

    public Son(IceBox iceBox) {
        this.iceBox = iceBox;
    }

    @Override
    public void run() {

        //不停的吃冰棍
        while (true) {
            if (IceBox.iceScreamNumber <= 0) {
                break;
            }

            iceBox.eatIceScream(); //所在线程调用同步方法
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


}

public class IceBox {

    public static int iceScreamNumber = 50; //冰箱里面的50根冰棍
    private int bigSonNum = 0; //大儿子吃的数量
    private int smallSonNum = 0; //小儿子吃的数量

    //定义冰箱对象的同步方法
    public synchronized void eatIceScream() {

        IceBox.iceScreamNumber--;
        if ("大林".equals(Thread.currentThread().getName())) {
            System.out.println("大林吃了一根冰棍，还剩：" + IceBox.iceScreamNumber + "根冰棍。");
            bigSonNum++;
        } else {
            System.out.println("小林吃了一根冰棍，还剩：" + IceBox.iceScreamNumber + "根冰棍。");
            smallSonNum++;
        }

    }

    public void showResult() {
        System.out.println("大林吃了：" + bigSonNum + "根。");
        System.out.println("小林吃了：" + smallSonNum + "根。");
    }


    public static void main(String[] args) {
        IceBox iceBox = new IceBox(); //冰箱对象。

        Son son = new Son(iceBox); //Runnable对象

        Thread bigTh = new Thread(son, "大林"); //大儿子线程对象
        Thread smallTh = new Thread(son, "小林"); //小儿子线程对象。

        bigTh.start();  //启动大儿子线程
        smallTh.start();//启动小儿子线程

        try {
            bigTh.join(); //等待两个线程结束
            smallTh.join();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        iceBox.showResult(); // 显示结果

    }
}
